const axios = require('axios');
const { geminiAI } = require('../google/gemini')
const { readSheet, updateSheet } = require('../google/sheet')
const { checkAuth, sendMail } = require('../google/gmail')
const config = require('../config')

// 获取日历信息
async function getTodayCalendarInfo () {
    const today = new Date();
    const formattedDate = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
    try {
        const response = await axios.get('http://v.juhe.cn/calendar/day', {
            params: {
                key: config.juhe.JUHE_API_KEY,
                date: formattedDate
            }
        });
        return response.data;
    } catch (error) {
        console.error('获取日历信息失败:', error);
        throw error;
    }
}
//读取生日表格
async function getGoogleSheetData (range, filterFn) {
    const datas = await readSheet(range);
    return typeof filterFn === 'function' ? datas.filter(filterFn) : datas
}
//生成文案
async function generateGreetingWithAI () {
    const prompt = "请帮我生成一句100字以内的早安问候语，内容积极向上、充满正能量,尽量语义化。直接输出文案短句, 无需输出推理相关其他的信息";

    try {
        return await geminiAI(prompt);
    } catch (error) {
        console.error('AI生成问候语失败:', error);
        return "愿你今天充满阳光和快乐！";
    }
}
// 执行工作流程
async function executeBirthDateWorkflow () {
    try {
        // 检查gmail。token 是否过期

        const resAuth = await checkAuth()
        console.log(resAuth)
        if (resAuth.code != 200) {
            console.log('邮件token过期!!!!!')
            console.log(resAuth.msg)
            return resAuth
        }
        // 1. 获取当前日期的日历信息
        const calendarData = await getTodayCalendarInfo();
        const lunarDate = calendarData.result.data.lunar;
        const date = calendarData.result.data.date;
        const weekday = calendarData.result.data.weekday;
        console.log(`今天是${lunarDate}`);

        // 2. 检查是否有农历生日
        // return await getGoogleSheetData('birthDate', (row) => row[3].trim() === lunarDate)
        const birthdayData = await getGoogleSheetData('birthDate', (row) => row[3].trim() === lunarDate)
        console.log(birthdayData);

        // 3. 如果有生日记录，发送生日提醒邮件
        if (birthdayData && birthdayData.length > 0) {
            // 这里应该构建生日提醒内容
            const birthdayMessage = `今天是${date}，农历${lunarDate}，${weekday}。有人过生日啦！`;
            await sendMail('生日提醒', `${birthdayMessage}\n\n${birthdayData[0][4]}`);
        } else {
            // 4. 获取状态为0的文案
            const originalCopywriting = await getGoogleSheetData('文案', (row) => row);
            const rowIndex = originalCopywriting.findIndex(row => row[1] == 0);
            const copywritingData = originalCopywriting.filter(row => row[1] == 0);

            let greetingMessage = '';

            if (copywritingData && copywritingData.length > 0) {
                // 使用已有文案
                const copywriting = copywritingData[0][0];
                greetingMessage = `早上好！今天是${date}，农历${lunarDate}，${weekday}\n\n${copywriting}`

                // 更新文案状态为已使用
                await updateSheet(`文案!B${rowIndex + 1}:B${rowIndex + 1}`, [[1]]);
            } else {
                // 使用AI生成问候语
                const aiGreeting = await generateGreetingWithAI();
                greetingMessage = `早上好！今天是${date}，农历${lunarDate}，${weekday}\n\n${aiGreeting}`;
            }
            // 5. 发送每日问候邮件
            await sendMail('你好，今天', greetingMessage);
        }
        console.log('工作流执行完成');
        return { success: true, code: 200 };
    } catch (error) {
        console.error('工作流执行出错:', error);
        return { success: false, error: error.message };
    }
}

module.exports = { executeBirthDateWorkflow }